<template>
  <div class="dialout" v-loading="loading">
    <div v-show="!isDrill">
      <div class="top">
        <div class="search">
          <div class="contition">
            <div class="wrap_time">
              <date-time type="other_half_hour"  @changeType="changeType" @changeDateS="childTimeChange" :query="query" @isFold="isShowFold" :isTimePeriod = "true" :isOther="true"></date-time>
                <el-button type="primary" class="primary_btn fr find" @click.stop='search'>{{$t('public.search2')}}</el-button>
                <div class="clear"></div></div>
            <div class="wrap_drop">
              <unfold :isShow="isFold" :title="[]">
                <template slot="unfoldSlot">
                  <div class="serve">
                    <span class="prov">{{$t('public.province')}}：</span>
                    <el-checkbox :indeterminate="isIndeterminate" v-model.trim="checkAll" @change="handleCheckAllChange">{{$t('public.checkAll')}}</el-checkbox>
                    <div style="margin: 15px 0;"></div>
                    <el-checkbox-group v-model.trim="checkedProvinces" @change="handleCheckedProvincesChange">
                      <el-checkbox v-for="(province, index) in provinces" :key="index" :label="province" :name="province">{{province}}</el-checkbox>
                    </el-checkbox-group>
                  </div>
                </template>
              </unfold></div>
          </div>
        </div>
        <affix :label="$t('report.callOutAreaSurvey')"></affix>
        <div class="situation">
          <div class="wrap_pro">
            <div class="call_all">
              <span>{{$t('report.outCallSum')}}</span>
              <span class="all_num">{{callInAll}}</span>
            </div>
            <div class="wrap_top" v-show="serveNumData.length !== 0">
              <span>{{$t('report.callOutTopPro')}}</span>
              <ul>
                <li v-for="(item, index) in situation" :key="index">
                  <span class="sum_name">{{item.name}}</span>
                  <span class="sit_num">{{item.value}}</span>
                </li>
              </ul>
            </div>
          </div>
        </div>
        <affix :label="$t('report.calloutAreaRe')"></affix>
      </div>
      <div class="tab" :id="id">
        <div class="export">
          <el-button class="primary_btn fr formal" v-if="configFormula" @click="$refs.formulaEditorDialog.open()">
            {{ $t('report.formalTitle') }}</el-button>
          <el-button class="primary_btn fr" v-on:click.stop="config" v-if="!configHeaderBool">{{$t('report.setHeaderConfig')}}</el-button>

          <!-- <el-button class="primary_btn fr report_excel_btn"
            v-if="$store.getters.exportFromEnd"
            v-on:click.stop="exportExcel"
          >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->

          <el-button class="primary_btn fr report_excel_btn"
            v-on:click.stop="exportXlsx"
          >{{$t('report.exportXls')}}</el-button>

          <el-button class="primary_btn fr pdf" v-on:click.stop="exportPdf">{{$t('report.exportPDF')}}</el-button>
        </div>
        <div class="deploy">
          <el-collapse accordion>
            <el-collapse-item>
              <template slot="title">
                  <span class="fl explain">{{$t('report.toggleInstructe')}}</span>
                </template>
              <div>
                {{$t('report.callOutNum')}}<br>
                {{$t('report.callOutSucNum')}}<br>
                {{$t('report.callOutRingNotAnsNum')}}<br>
                {{$t('report.callOutFailNum')}}<br>
                {{$t('report.callOutSucRate')}}<br>
                {{$t('report.callOutAllTime')}}<br>
                {{$t('report.callOutAverTime')}}
                <p class="custom_alg">{{ $t('report.ziDingYi') }}：</p>
                <p v-for="(item, index) in formulas" :key="item.name">
                  {{ index + 8 }}.{{ item.formulaInstr }}
                </p>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <report-table :data="serveNumData" :sum="sum" :config="[...headOptions.Config, ...formulasConfig]" @proName ="intiCondition"> </report-table>
      </div>
    </div>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
      <span>{{$t('report.reportExportTipTitle')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
        <el-button class="primary_btn" type="primary" @click="confirm">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
    <header-option v-show="isShow" :show="isShow" :option="headOptionsShow" type="call_report_dialout_area" v-on:close="close" :headCustom="formulasConfig"></header-option>
    <opendialoutarea v-show="isDrill" ref="myChild" :condition = "{province, Query, dateSource}" @flag="turnPage"></opendialoutarea>
    <!-- 自定义公式组件 -->
    <FormulaEditorDialog ref="formulaEditorDialog" :headOptionsConfig="headOptions.Config"
      @closeFormulaDialog="closeFormulaDialog" reportName="呼出地域分布报表" :reportType="id" />
  </div>
</template>
<script>
  import affix from '../../../ui-modules/affix/Affix.vue'
  import unfold from '../../../ui-modules/unfold/index.vue'
  import dateTime from '../base/dateDrill.vue'
  import headerOption from '../base/headerOption.vue'
  import {exportReportPdf, checkTime, searchTime, headOptionsToXlsxHeaders, reportAreaProvince, mixData} from '@/utils/reportUtils.js'
  import {deepClone, getCallTimeLength, optionTimeTypeCheck, isHasFunc} from '@/utils/m7Utils.js'
  import reportTable from '../base/drillInto.vue'
  import opendialoutarea from './OpenDialoutArea.vue'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'
  import {sortBy} from 'lodash'
  import FormulaEditorDialog from '../base/FormulaEditorDialog.vue'

  export default {
    name: 'dialout',
    data () {
      return {
        configFormula: true, // 自定义公式的权限
        formulas: [], // 公式数据
        resData: [], // 返回数组暂存
        isFold: false, // 是否展示搜索条件
        situation: [], // 概况渲染数据
        callInAll: 0, // 外呼总数
        dateSource: {}, // 钻入需要的数据
        isDrill: false, // 是否显示当前组件或钻入组件开关
        loading: false, // 查询时展示加载的开关
        id: 'call_report_dialout_area', // 查询id
        query: {}, // 查询条件时间信息等
        isShow: false, // 是否展示配置表头开关
        dialogVisible: false, // 导出pdf弹窗开关
        checkAll: true, // 省份全选绑定值
        checkedProvinces: [], // 多选绑定选择省份值
        isIndeterminate: false, // 全选样式调控值
        headOptions: { // 表头数据
          Config: []
        },
        headOptionsShow: {}, // 配置表头用的数据
        provinces: reportAreaProvince, // 省份数据
        sum: [], // 表格合计数据
        serveNumData: [], // 表格table除合计数据
        Query: {},
        province: '',
        dateType:""
      }
    },
    components: {
      affix,
      unfold,
      dateTime,
      headerOption,
      reportTable,
      opendialoutarea,
      FormulaEditorDialog
    },
    computed: {
      // 判断是否展示配置表头
      configHeaderBool () {
        return this.$store.state.report.setConfigHeaderBool
      },
      // 自定义表头
    formulasConfig() {
      return this.formulas.map((d, i) => {
        return {
          displayname: d.displayname,
          name: d.name,
          order: d.order,
          show: d.show,
          timeType: 'none',
          digits: d.digits,
          type: d.type
        }
      })
    }
    },
    methods: {
      // 自定义公式弹窗关闭外抛事件
      closeFormulaDialog() {
        this.isSearch = false
        this.$store.dispatch('queryFetchFormula', { type: this.id }).then((resp) => {
          if (resp.success) {
            this.formulas = resp.data.Formulas
          }
        })
      },
      // 子组件切换时间类型传上来得方法
      changeType (type) {
        this.dateType = type
      },
      // 钻入需要渲染的原始时间数据, 子组件传过来的方法
      childTimeChange (obj) {
        this.dateSource = obj
      },
      // 是否展开收起查询条件
      isShowFold (bool) {
        this.isFold = bool
      },
      // 钻入的子组件传上来的方法 展示当前页
      turnPage () {
        this.isDrill = false
      },
      // 渲染钻入组件的查询条件
      intiCondition (province) {
        this.province = province
        // 判断省是否为空
        if (this.checkedProvinces.length === 0) {
          this.isProvince()
        }
        let self = this
        this.provinces.forEach(function (item) {
          if (self.checkedProvinces.indexOf(item) >= 0) {
            self.query['Province_' + item] = true
          } else {
            self.query['Province_' + item] = false
          }
        })
        let myQuery = deepClone(this.query)
        myQuery.TimeType = myQuery.timeType
        delete myQuery.timeType
        myQuery.relayAreaCityCurrentProvince = ''
        this.Query = deepClone(myQuery)
        //钻入的数据里周报查询条件为other
        if(this.dateType == 'week'){
          this.Query.TimeType = 'other'
        }
        this.isDrill = true
        this.$nextTick(() => {
          this.$refs.myChild.search1()
        })
      },
      // 抽出查询条件
      getSearchQueryData () {
        if (this.checkedProvinces.length === 0) {
          this.isProvince()
          return
        }
        // 初始化查询条件
        let data = {
          reportType: 'call_report_dialout_area',
          account: this.$store.state.session.user.account
        }
        let self = this
        this.provinces.forEach(function (item) {
          if (self.checkedProvinces.indexOf(item) >= 0) {
            self.query['Province_' + item] = true
          } else {
            self.query['Province_' + item] = false
          }
        })
        let myQuery = deepClone(this.query)
        if (myQuery.timeType === 'other_half_hour') {
          let message = null;
          if (this.dateType === 'week') { // 周报允许到天
            myQuery.timeType = 'other'
            message = checkTime(myQuery.StartTime, myQuery.EndTime, false, true) // 校验类型与时间
          } else {
            message = checkTime(myQuery.StartTime, myQuery.EndTime, false, false) // 校验类型与时间
          }
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        myQuery.TimeType = myQuery.timeType
        delete myQuery.timeType
        data['query'] = myQuery
        return data
      },
      // 获取表格合计数据
      // getServeNumDataAndSum (headOptions, tempData) {
      //   var sum = [{Province: this.$t('report.total')}]
      //   for (let i in tempData) {
      //     let item = tempData[i]
      //     for (let j in item) {
      //       if (sum[0][j] === undefined) {
      //         sum[0][j] = 0
      //       }
      //       if (j !== 'Province') {
      //         sum[0][j] += item[j]
      //       }
      //     }
      //     headOptions.Config.forEach((option, index) => {
      //       if (option.timeType && option.timeType === 'hhmmss') {
      //         item[option.name] = getCallTimeLength(item[option.name])
      //       } else if (option.timeType && option.timeType === 'second') {
      //         item[option.name] = Math.round(item[option.name]) + 's'
      //       }
      //     })
      //   }
      //   if (tempData.length > 0) {
      //     sum[0].CallOutAcceptRate = sum[0].AccessCount === 0 ? '0%' : Math.round((sum[0].DealingCount / sum[0].AccessCount) * 100) + '%'
      //     sum[0].CallOutAverageTimeLength = Math.round(sum[0].CallTimeLength / sum[0].DealingCount) || 0
      //     headOptions.Config.forEach((option, index) => {
      //       if (option.timeType && option.timeType === 'hhmmss') {
      //         sum[0][option.name] = getCallTimeLength(sum[0][option.name])
      //       } else if (option.timeType && option.timeType === 'second') {
      //         sum[0][option.name] = Math.round(sum[0][option.name]) + 's'
      //       }
      //     })
      //   }
      //   return sum
      // },
      // 获取合计和处理data
    getServeNumDataAndSum(myQuery) {
      let sum = { Province: this.$t('report.total') }
      let tempData = deepClone(mixData(this.resData, this.formulas))
      for (let i in tempData) {
        let item = tempData[i]
        // 计算合计
        for (let j in item) {
          if (sum[j] === undefined) {
            sum[j] = 0
          }
          if (j !== 'Province') {
            sum[j] += item[j]
          }
        }
        this.headOptions.Config.forEach((option, index) => {
          if (option.name.indexOf('Rate') > -1 && option.displayname.indexOf('率') > -1) {
              item[option.name] = `${item[option.name]}`
          }
          if (option.timeType && option.timeType === 'hhmmss') {
            item[option.name] = getCallTimeLength(item[option.name])
          } else if (option.timeType && option.timeType === 'second') {
            item[option.name] = Math.round(item[option.name]) + 's'
          }
        })
      }

      sum = mixData([sum], this.formulas)
      sum[0].CallOutAcceptRate = sum[0].AccessCount === 0 ? '0%' : Math.round((sum[0].DealingCount / sum[0].AccessCount) * 100) + '%'
      sum[0].CallOutAverageTimeLength = Math.round(sum[0].CallTimeLength / sum[0].DealingCount) || 0
      this.headOptions.Config.forEach((option, index) => {
        if (option.timeType && option.timeType === 'hhmmss') {
          sum[0][option.name] = getCallTimeLength(sum[0][option.name])
        } else if (option.timeType && option.timeType === 'second') {
          sum[0][option.name] = Math.round(sum[0][option.name]) + 's'
        } 
      })
      return {
        sum: sum,
        dataDeal: sortBy(tempData, 'Province'),
      }
        
        
    },
      // 查询方法
      search() {
        var data = this.getSearchQueryData()
        if (!data) {
          return
        }
        var myQuery = data.query
        this.loading = true
        this.situation = []
        this.$store.dispatch('queryCallDialoutAreaReport', data).then((res) => {
          if (this.$store.state.report.customExportData) {
            res = JSON.parse(this.$store.state.report.customExportData)
          }
          if (!res.success) {
            this.loading = false
            return
          }
          this.$store.dispatch('queryFetchFormula', { type: this.id }).then((resp) => {
            if (resp.success) {
              this.formulas = resp.data.Formulas
              this.resData = res.data
              this.headOptions = optionTimeTypeCheck(res.tableHeader)
              this.sum = [{ Province: this.$t('report.total') }]
              let tempData = deepClone(res.data)
              if (!tempData || tempData.length === 0) {
                this.sum = [{}]
                this.callInAll = 0
                this.serveNumData = []
                this.loading = false
                return
              }
              tempData = sortBy(tempData, (item) => {
                return -item.AccessCount
              })
              let { sum, dataDeal } = this.getServeNumDataAndSum(myQuery)
              this.sum = sum
              // 数据排序
              this.serveNumData = sortBy(dataDeal, 'Province')


              for (let i in tempData) {
                let item = tempData[i]
                // 渲染前五得省份
                if (i < 5) {
                  this.situation.push({ name: item._id, value: item.AccessCount })
                }
              }

              this.callInAll = this.sum[0].AccessCount || 0
              this.serveNumData = tempData
              this.loading = false

            }
          })


        })
      },
      // 导出表格数据执行的方法(前端)
      exportXlsx () {
        var data = this.getSearchQueryData()
        if (!data) {
          return
        }
        var myQuery = data.query
        this.loading = true
        this.situation = []
        this.$store.dispatch('queryCallDialoutAreaReport', data).then((res) => {
          if (this.$store.state.report.customExportData) {
            res = JSON.parse(this.$store.state.report.customExportData)
          }
          if (!res.success) {
            this.loading = false
            return
          }
          this.loading = false
          var headOptions = optionTimeTypeCheck(res.tableHeader)
          // let tempData = deepClone(res.data)
          let { sum, dataDeal } = this.getServeNumDataAndSum(myQuery)
          // 排序之后合并合计数组
          var tableData = sortBy(dataDeal, 'ReportTime').concat(sum)

          var headers = headOptionsToXlsxHeaders([...headOptions.Config, ...this.formulasConfig])

          var dh = XlsxUtil.getDownloadHelper(headers, tableData)
          var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
          dh.download(this.$t('report.callReportDialoutArea') + timeStamp)
        })
      },
      // 关闭配置表头弹窗,如果点击保存则查询重新渲染数据
      close (data) {
        this.isShow = false
        if (data === 'save') {
          this.search()
        }
      },
      // 判断查询条件是否为空
      isProvince () {
        this.$message.error(this.$t('report.searchProvince'))
      },
      // 配置表头
      config () {
        this.$store.dispatch('getReportTableHeader', 'call_report_dialout_area').then((res) => {
          this.headOptionsShow = optionTimeTypeCheck(res)
          this.isShow = !this.isShow
        })
      },
      // 导出PDF
      exportPdf () {
        this.dialogVisible = true
      },
      // 确认导出pdf执行的方法
      confirm () {
        this.dialogVisible = false
        exportReportPdf({title: this.$t('report.callReportDialoutArea') + searchTime(this.query), id: this.id})
      },
      // 导出表格数据执行的方法(后端)
      exportExcel () {
        let self = this
        this.provinces.forEach(function (item) {
          if (self.checkedProvinces.indexOf(item) >= 0) {
            self.query['Province_' + item] = true
          } else {
            self.query['Province_' + item] = false
          }
        })
        let myQuery = deepClone(this.query)
        if (myQuery.timeType === 'other_half_hour') {
          myQuery.timeType = 'other'
          let message = checkTime(myQuery.StartTime, myQuery.EndTime, false, true) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        myQuery.TimeType = myQuery.timeType
        delete myQuery.timeType
        myQuery.reportType = 'call_report_dialout_area'
        myQuery.accountId = this.$store.state.session.user.account
        myQuery.type = 'ReportDialoutAreaExport'
        myQuery.user = this.$store.state.session.user._id
        let data = {
          Method: 'ReportDialoutAreaExport',
          Query: myQuery
        }
        this.$store.dispatch('exportCallDialoutAreaReport', data).then(() => {
        })
      },
      // 全选，参考饿了么
      handleCheckAllChange (event) {
        this.checkedProvinces = this.checkAll ? this.provinces : []
        this.isIndeterminate = false
      },
      // 选择省份触发的方法
      handleCheckedProvincesChange (value) {
        let checkedCount = value.length
        this.checkAll = checkedCount === this.provinces.length
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.provinces.length
      }
    },
    watch: {
    // 监测自定义公式变化 更新数据
    formulas(cur, old) {
      if (this.isSearch) {
        return
      }
      if (!this.serveNumData || this.serveNumData.length === 0) {
        return
      }
      var queryData = this.getSearchQueryData()
      if (!queryData) {
        return
      }
      var myQuery = queryData.query
      let { sum, dataDeal } = this.getServeNumDataAndSum(myQuery)
      this.sum = sum
      this.serveNumData = dataDeal
    }
  },
    beforeMount () {
      if (isHasFunc('func_forbid_config_formula', this.$store.state.session.user)) {
        this.configFormula = false // 没有自定义公式的配置权限
      }
      this.handleCheckAllChange()
      this.search()
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .serve
    .el-checkbox
      width 90px
  .formal
    margin-left 10px  
</style>
